#pragma once
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include "task.hpp"

static const int defaultnum = 5;

struct ThreadInfo{
    pthread_t tid;
    std::string name;
};

template<class T>
class ThreadPool{
public:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool QueueIsEmpty()
    {
        return _tasks.empty();
    }
    std::string GetThreadName(pthread_t tid)
    {
        for (const auto& ti : _threads)
        {
            if (ti.tid == tid) return ti.name;
        }
        return "None";
    }
public:
    static void* HanderTask(void* args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while(true)
        {
            tp->Lock();
            while(tp->QueueIsEmpty())
            {
                tp->ThreadSleep();
            }
            T t = tp->Pop();
            tp->UnLock();

            t();
            std::cout << name << " is running, " << "result: " << t.GetResult() << std::endl << std::endl;
        }
    }
    void Run()
    {
        int num = _threads.size();
        for(int i = 0; i < num; i++)
        {
            _threads[i].name = "thread-" + std::to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, HanderTask, this);
        }
    }
    void Push(const T& t)
    {
        Lock();
        _tasks.push(t);
        Wakeup();
        UnLock();
    }
    T Pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    static ThreadPool<T>* GetInstance()
    {
        if(nullptr == _tp) // 双重判断，保证多线程并发安全的同时提高效率
        {
            pthread_mutex_lock(&_lock);
            if(_tp == nullptr)
            {
                std::cout << "log: singleton create done firstly!" << std::endl << std::endl;
                _tp = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_lock);
        }

        return _tp;
    }
private:
    ThreadPool(int num = defaultnum)
    :_threads(num)
    {}
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
    ThreadPool(const ThreadPool<T>&) = delete;
    const ThreadPool<T>& operator=(const ThreadPool<T>&) = delete;

private:
    std::vector<ThreadInfo> _threads;
    std::queue<T> _tasks;

    pthread_mutex_t _mutex; // 锁 实现互斥
    pthread_cond_t _cond;  // 信号量 实现同步

    static ThreadPool<T>* _tp;
    static pthread_mutex_t _lock;
};

template<class T>
ThreadPool<T>* ThreadPool<T>::_tp = nullptr;
template<class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;